import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { escapeData, unEscapeData } from './tools'
import { updateCookiesMaxAge } from './util'
import config from '@/config'

const adminMenuList = [
  {
    'id': 27,
    'name': 'agent',
    'urlname': '/agent/info',
    'titlename': '\\u8fd0\\u8425\\u5546\\u4fe1\\u606f\\u7ba1\\u7406',
    'pid': 0
  },
  {
    'id': 28,
    'name': 'agent_info',
    'urlname': '/agent/info',
    'titlename': '\\u8fd0\\u8425\\u5546\\u4fe1\\u606f\\u7ba1\\u7406',
    'pid': 27
  }
]

const addErrorLog = errorInfo => {
  const {
    statusText,
    status,
    request: { responseURL }
  } = errorInfo
  const info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) {
    store.dispatch('addErrorLog', info)
  }
}

class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          // Spin.show() // 不建议开启，因为界面不友好
        }
        this.queue[url] = true
        const data = _.cloneDeep(config.data)
        escapeData(data)
        config.data = data
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        updateCookiesMaxAge()
        this.destroy(url)
        const { data, status } = res
        if (data.desc == 'token not exist') {
          store.dispatch('handleLogOut').then(() => {
            router.push({
              name: 'login'
            })
          })
        }
        if (status == 200) {
          typeof data.data === 'string' && (data.data = data.data === '' ? {} : JSON.parse(data.data))

          // TODO
          // 由于后台返回的是错误的menulist, 因此这里为了推进项目，模拟正确的menulist值
          // 待后台改正后去掉此代码
          if (url == config.api.login) {
            const { menulist, operatorid, stationid, username } = data.data
            if (operatorid == 0 && stationid == 0) {
              // 超级管理员
              data.data.menulist = adminMenuList
            }
          }

          unEscapeData(data)
          return data
        } else {
          return {
            code: 5000,
            desc: 'request exception!'
          }
        }
      },
      error => {
        updateCookiesMaxAge()
        this.destroy(url)
        let errorInfo = error.response
        if (!errorInfo) {
          const {
            request: { statusText, status },
            config
          } = JSON.parse(JSON.stringify(error))
          errorInfo = {
            statusText,
            status,
            request: { responseURL: config.url }
          }
        }
        // addErrorLog(errorInfo)
        return Promise.reject(error)
      }
    )
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
